package com.example.administrator.myview.service;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;

/**
 * Created by Administrator on 2017/12/8.
 */

public class ServiceActivity extends Activity {

    private MyService myService;
    private MyService.LocalBinder localBinder;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //这两个方法写到需要点击事件里 启动和关闭服务
        startService();
        stopService();
    }

    //暂停服务
    private void stopService() {
        //进行判断 是否开启了服务
        if (localBinder.isStartMyService()){

        }else {
            myService.stopMyService();
        }
    }

    //开始服务
    private void startService() {
        //进行判断 是否开启了服务
        if (localBinder.isStartMyService()){

        }else {
            myService.startMyService();
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        Intent intent =new Intent(this,MyService.class);
        bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //通过这个得到绑定后的回调得到服务对象
    private ServiceConnection serviceConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //得到服务对象
            myService=localBinder.getMyService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };
}
